<?php

class Damages_Emails {

  const PASSWORD_RESET_TITLE = 'Baza Szkód VGP - hasło użytkownika.';
  const TEMPLATE_REGEX = '/(\[\[%s\]\])/';

  /**
   *
   * @var PHPMailer 
   */
  public $phpMailer;

  public function __construct($silent = false) {
    require_once 'class.phpmailer.php';
    $config = Damages_Config::getInstance()->email->notifications;
    $this->phpMailer = new PHPMailer();
    $this->phpMailer->CharSet = $config->charSet;
    $this->phpMailer->IsSMTP(true);
    $this->phpMailer->Sender = $config->from;
    $this->phpMailer->SMTPDebug = (bool) $config->smtp->debug;
    if ($silent)
      $this->phpMailer->SMTPDebug = false;
    $this->phpMailer->SMTPAuth = (bool) $config->smtp->auth;
    $this->phpMailer->Host = $config->smtp->host;
    $this->phpMailer->Port = $config->smtp->port;
    if ($config->smtp->auth) {
      $this->phpMailer->SMTPSecure = $config->smtp->secure;
      $this->phpMailer->Username = $config->smtp->user;
      $this->phpMailer->Password = $config->smtp->password;
    }
    $this->phpMailer->From = $config->from;
    $this->phpMailer->FromName = $config->fromName;
  }

  public static function addEmail($carDamageId, $baseTemplateId, $content, $recipient) {
    $dbObject = new DamagesEmails();
    $dbObject->setCarDamageId($carDamageId);
    $dbObject->setBaseTemplateId($baseTemplateId);
    $dbObject->setEmailContent($content);
    $dbObject->setRecipient($recipient);
    $dbObject->save();
    return $dbObject->getId();
  }

  public function processMailQueue() {
    $viewDir = Zend_Controller_Front::getInstance()->getModuleDirectory('damages') . '/views/scripts/partials/';
    $view = new Zend_View();
    $view->setScriptPath($viewDir);

    $emails = $this->getEmails();
    foreach ($emails as $email) {
      try {
        $template = DamagesEmailTemplatesQuery::create()->findOneById($email->getBaseTemplateId());
        $this->phpMailer->ClearAttachments();
        switch ($template->getCode()) {
          case 'et1':
            $carDamage = DamagesCarDamagesQuery::create()->findOneById($email->getCarDamageId());
            foreach ($carDamage->getAttachmentss() as $attachment) {
              $this->phpMailer->AddAttachment(APPLICATION_PATH . '/../public' . $attachment->getFilePath());
            }
            $estimatedBudget = DamagesEstimatedBudgetsQuery::create()
                    ->filterByCarDamageId($email->getCarDamageId())
                    ->filterByIsDefault(1)
                    ->findOne();
            if ($estimatedBudget && $estimatedBudget->getAttachments()) {
              $this->phpMailer->AddAttachment(APPLICATION_PATH . '/../public' . $estimatedBudget->getAttachments()->getFilePath());
            }
            break;
          case 'sd1':
            $estimatedBudget = DamagesEstimatedBudgetsQuery::create()
                    ->filterByCarDamageId($email->getCarDamageId())
                    ->filterByIsDefault(1)
                    ->findOne();
            if ($estimatedBudget && $estimatedBudget->getAttachments()) {
              $this->phpMailer->AddAttachment(APPLICATION_PATH . '/../public' . $estimatedBudget->getAttachments()->getFilePath());
            }
            break;
          case 'vq1':
            $resultDir = APPLICATION_PATH . Damages_Config::getInstance()->xls->tmp->path;
            $resultPath = $resultDir . sprintf(Damages_Config::getInstance()->xls->tmp->file, $email->getId());
            $this->phpMailer->AddAttachment($resultPath, Damages_Config::getInstance()->xls->file);
            break;
          default:
            break;
        }
        $this->phpMailer->ClearAddresses();
//        $emails = explode(',', $email->getRecipient());
        $emails = preg_split('/(\s|,)/', $email->getRecipient());
        foreach ($emails as $mail) {
          if (trim($mail))
            $this->phpMailer->AddAddress(trim($mail));
        }
        $this->phpMailer->IsHTML(true);
        $this->phpMailer->AddBCC('samochody-szkody@vw-group.pl');
        if ($template->getTitleTemplate()) {
          $carDamage = DamagesCarDamagesQuery::create()->findOneById($email->getCarDamageId());
          $view->carDamage = $carDamage;
          $title = $template->getTitleTemplate();
          foreach (Damages_Tags::getInstance()->getList() as $value) {
            if (preg_match(sprintf(Damages_Emails::TEMPLATE_REGEX, $value->code), $title)) {
              $data = $view->render($value->code . '.phtml');
              $title = preg_replace(sprintf(Damages_Emails::TEMPLATE_REGEX, $value->code), $data, $title);
            }
          }
        } else {
          $title = $template->getName();
        }
        $this->phpMailer->Subject = $title;
        $this->phpMailer->Body = $email->getEmailContent();
        $this->phpMailer->AltBody = strip_tags(preg_replace('#<br\s*/?>#i', "\n", $email->getEmailContent()));
        if ($this->phpMailer->Send()) {
          $email->setStatus(2);
          $email->save();
        }
      } catch (Exception $exc) {
        continue;
      }
    }
  }

  private function getEmails() {
    $q = DamagesEmailsQuery::create()->filterByStatus(0);
    return $q->find();
  }

  public function sendNewPasswordNotification(DamagesUsers $user, $password) {
    $viewDir = Zend_Controller_Front::getInstance()->getModuleDirectory('damages') . '/views/scripts/partials/';
    $view = new Zend_View();
    $view->setScriptPath($viewDir);
    $view->password = $password;
    $view->email = $user->getEmail();
    $body = $view->render('password.phtml');

    $this->phpMailer->ClearAttachments();
    $this->phpMailer->ClearAddresses();
    $this->phpMailer->AddAddress($user->getEmail());
    $this->phpMailer->IsHTML(true);
    $this->phpMailer->Subject = self::PASSWORD_RESET_TITLE;
    $this->phpMailer->Body = $body;
    $this->phpMailer->AltBody = strip_tags(preg_replace('#<br\s*/?>#i', "\n", $body));
    $this->phpMailer->Send();
  }

}